<?php

declare(strict_types=1);

namespace app\common\model;

use think\facade\Cache;
use app\common\controller\Config;
use addons\Target\facade\Target;


class PreceptOrder extends Base

{
    protected $name = 'precept_order';
    protected $type = [
        'pay_time'     => 'timestamp',
    ];

    public function getPayWayAttr($value)
    {
        return get_pay_way($value);
    }
    /**
     * 支付方案
     */
    public static function pay($param, $user)
    {
        $sys = Config::lists();
        parent::startTrans();
        try {
            $account = $param['pay_way'];
            $order = parent::where(['uid' => $user->id,'precept_id'=>$param['id'], 'pay_state' => 1])->find();
            if (!empty($order)) {
                return ['code' => -1, 'msg' => '方案订单已支付'];
            }
            $news = Precept::where(['id' => $param['id'], 'uid' => $user->id])->find();
            if (empty($news)) {
                return ['code' => -1, 'msg' => '方案不存在'];
            }
            if ($news->status != 4) {
                return ['code' => -1, 'msg' => '方案状态不正确'];
            }
            if (empty($account)) {
                return ['code' => -1, 'msg' => '请选择支付方式！'];
            }
            $max_discount = round($sys['d_discount'] * $news->price, 2);
            if ($param['discount'] > $max_discount) {
                return ['code' => -1, 'msg' => '本次方案佣金最多抵扣：￥' . $max_discount];
            }
            $real_price = round(floatval($news->price) - floatval($param['discount']), 2);
            $info = parent::create(
                [
                    'sn' => 'P' . date('YmdHis') . $user->id . rand(100000, 999999),
                    'uid' => $user->id,
                    'precept_id' => $param['id'],
                    'price' => $news['price'],
                    'discount' => $param['discount'],
                    'real_price' => $real_price,
                ]
            );
            parent::commit();
            switch ($account) {
                case "currency":
                    if ($user->assets->$account < $info->real_price) {
                        return ['code' => -1, 'msg' => '余额不足'];
                    }
                    return self::operations($info, $user, $account);
                case "wechat":
                    if ($info->discount > 0) {
                        if ($user->assets->bonus < $info->discount) {
                            return ['code' => -1, 'msg' => '佣金不足'];
                        }
                    }
                    $notifyUrl = 'https://' . $_SERVER['HTTP_HOST'] . '/api/callback/wechatPreceptOrder';
                    $options = \addons\Pay\facade\Pay::setDriver('WeChat')
                        ->basic('购买方案', $info->sn, $info->real_price, $notifyUrl)
                        ->setOpenId($user->openid)
                        ->create('JSAPI');
                    return ['code' => 1, 'msg' => '获取成功', 'options' => $options];
                default:
                    return ['code' => -1, 'msg' => '支付方式错误！'];
            }
        } catch (\Exception $e) {
            parent::rollback();
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }
    /**
     * 支付回调
     */

    public static function operations($info, $user, $account): array
    {
        $sys = Config::lists();
        parent::startTrans();
        try {
            Precept::where(['id' => $info->precept_id])->update(['status' => 5]);
            $info->pay_way = $account;
            $info->pay_state = 1;
            $info->pay_time = time();
            $info->status = 2;
            $info->save();
            if (!in_array($account, ['wechat', 'alipay'])) {
                Target::Account()->basics($user->id, $account, $info->real_price, '方案支付', '-')
                    ->createNormal();
            }
            if ($info->discount > 0) {
                Target::Account()->basics($user->id, 'bonus', $info->discount, '方案支付佣金抵扣', '-')
                    ->createNormal();
            }
            if ($user->parent_id != 0) {
                Target::Account()->basics($user->parent_id, 'bonus', round($info->real_price * $sys['tp_1'], 2), '方案支付佣金', '+')
                    ->createBonus($user->id, 1);
            }
            parent::destroy(['uid' => $user->id, 'pay_state' => 0], true);
            parent::commit();
            return ['code' => 1, 'msg' => '支付成功'];
        } catch (\Exception $e) {
            parent::rollback();
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }
}
